package com.db.history.tests;

import com.db.history.messages.Message;
import com.db.history.messages.MessageHistory;

/**
 * Testing MessageHistory with several threads
 *
 */
public class MessageTestWithThreads {

    /**
     * 3 tests.
     * First - 10 writing threads, 3 reading threads, each thread send 10 messages. Each reader thread read messages 2 times with interval = 500ms.
     * Second - 1 writing threads, 5 reading threads, each thread send 1000 messages. Each reader thread read messages 2 times with interval = 10ms. Last reader read MessageHistory when it's not full (writers aren't finished)
     * First - 10 writing threads, 10 reading threads, each thread send 10 messages. Each reader thread read messages 10 times without interval.
     * @param args
     */
    public static void main(String[] args) {
        makeTest(10, 3, 10, 2, 500);

        makeTest(1, 5, 1000, 2, 10);

        makeTest(10, 10, 10, 10, 0);
    }

    /**
     * Creating @param writeThreadsNumber threads for writing messages to MassageList
     * Creating @param readThreadsNumber threads for reading messages from MessageHistory
     * Each writing thread write @param messageNumber messages
     * Each reading thread @param timesToRead read messages with time interval = @param sleepTime ms
     */
    private static void makeTest(int writeThreadsNumber, int readThreadsNumber, int messageNumber, int timesToRead, int sleepTime) {
        new Thread(() -> {
            MessageHistory mq = new MessageHistory();

            for (int n = 0; n < writeThreadsNumber; n++) {
                new Thread(() -> {
                    for (int i = 0; i < messageNumber; i++)
                        mq.addMessage(new Message(Thread.currentThread().getName(), "AnyText" + " " + i));
                }).start();
            }

            for (int n = 0; n<readThreadsNumber; n++) {
                new Thread(() -> {
                    for (int i = 0; i < timesToRead; i++) {
                        System.out.println(new StringBuffer(Thread.currentThread().getName() + " reading thread\n").append(mq.getMessages()).append("----------------------------------------------"));
                        try {
                            Thread.sleep(sleepTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }).start();
    }
}
